package CrowdCountingMVC.CCControler;

import CrowdCounting.Model.Util;
import CrowdCountingMVC.CCModel.CrowdCountingModelInterface;
import CrowdCountingMVC.CCView.CCShow.CrowdCountingShow;
import CrowdCountingMVC.ExceptionInfo.InputException;

import java.util.logging.Level;

import static Const.State.*;

public class CrowdCountingController implements CrowdCountingControllerInerface {
    CrowdCountingModelInterface ccModel;
    CrowdCountingShow ccShow;

    private boolean segmentInputFlag = false;
    private boolean thresholdInputFlag = false;

    public CrowdCountingController(CrowdCountingModelInterface model, int wight, int height) {
        ccModel = model;
        ccShow = new CrowdCountingShow(model, this, wight, height);
        ccShow.showCrowdCounting();
        ccModel.registerCrowdShowObserver(ccShow);
        ccModel.registerWarningShowObserver(ccShow);
        ccModel.registerPersonNumShowObserver(ccShow);
    }

    @Override
    public void start() throws InputException {
        checkCmdParam();
        if (ccModel.getShowState() == START) return;
        ccModel.start();
    }

    @Override
    public void stop() {
        if (ccModel.getShowState() == STOP || ccModel.getShowState() == CLOSE) return;
        ccModel.stop();
    }

    @Override
    public void end() {
        if (ccModel.getShowState() == CLOSE) return;
        ccModel.end();
        segmentInputFlag = false;
        thresholdInputFlag = false;
    }

    @Override
    public void inputSegmentParam(String param) throws InputException {
        if (segmentInputFlag) throw new InputException("请勿重复键入");
        checkTextInput(param);
        ccModel.inputParam(param);
        segmentInputFlag = true;
    }

    @Override
    public void inputThresholdParam(String param) throws InputException {
        if (!segmentInputFlag) {
            throw new InputException("请按顺序键入参数");
        }
        if (thresholdInputFlag) throw new InputException("请勿重复键入");
        checkTextInput(param);
        ccModel.inputParam(param);
        thresholdInputFlag = true;
    }

    public void checkTextInput(String input) throws InputException {
        if (ccModel.getShowState() != CLOSE) {
            Util.logger(Level.INFO, "The application is already started, so you can't set it. Input = " + input);
            throw new InputException("应用运行中，无法设置参数");
        }
        if (!Util.isNumeric(input)) {
            Util.logger(Level.INFO, "The type of input is wrong. Input" + input);
            throw new InputException("参数类型有误");
        }
        Util.logger(Level.INFO, "User enter:" + input);
    }

    public void checkCmdParam() throws InputException {
        int rightCmdLength = ccModel.getPythonRunTask().getCmdList().size() + (ccModel.getPythonRunTask().getIsBufferOut() ? 0 : 1);
        if (rightCmdLength < 3 || rightCmdLength == 4) {
            throw new InputException("请键入必要参数");
        }
    }

}
